package com.zhongshengnetwork.rightbe.common;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;

/**
 * Created by zhongsheng-luojianlan on 16/12/31.
 */

public class PermissionUtils {
    /**
     *  返回true 表示可以使用  返回false表示不可以使用
     */
    public static boolean cameraIsCanUse() {
        boolean isCanUse = true;
        if (android.os.Build.VERSION.SDK_INT < 23){//6.0以下
            Camera mCamera = null;
            try {
                mCamera = Camera.open();
                Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
                mCamera.setParameters(mParameters);
            } catch (Exception e) {
                isCanUse = false;
            }

            if (mCamera != null) {
                try {
                    mCamera.release();
                } catch (Exception e) {
                    e.printStackTrace();
                    return isCanUse;
                }
            }

        }else {
            PackageManager packageManager = CustomApplication.mContext.getPackageManager();
            int permission = packageManager.checkPermission("android.permission.CAMERA", "com.zhongshengnetwork.rightbe");
            if(PackageManager.PERMISSION_GRANTED == permission){
                //有这个权限
                isCanUse = true;
            }else {
                //没有这个权限
                isCanUse = false;
            }
            Log.e("TAG","权限值="+permission);
        }
        return isCanUse;
    }

    // 音频获取源
    public static int audioSource = MediaRecorder.AudioSource.MIC;
    // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
    public static int sampleRateInHz = 44100;
    // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    public static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
    // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
    public static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    // 缓冲区字节大小
    public static int bufferSizeInBytes = 0;
    /**
     * 判断是是否有录音权限
     */
    public static boolean isHasRecordPermission(){
        bufferSizeInBytes = 0;
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
                channelConfig, audioFormat);
        AudioRecord audioRecord =  new AudioRecord(audioSource, sampleRateInHz,
                channelConfig, audioFormat, bufferSizeInBytes);
        //开始录制音频
        try{
            // 防止某些手机崩溃，例如联想
            audioRecord.startRecording();
        }catch (IllegalStateException e){
            e.printStackTrace();
        }
        /**
         * 根据开始录音判断是否有录音权限
         */
        if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
            return false;
        }
        audioRecord.stop();
        audioRecord.release();
        audioRecord = null;

        return true;
    }

    /**
     * 检查外部存储是否可读写（可写隐含可读）
     */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /**
     * 检查外部存储是否至少可读
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    //相册和存储权限
    public static void isPictureNote(Context context, PermissionCallback callback){
        Boolean flag = SPManageUtils.getInstance(context).getSPBoolean("pictureNote", false);
        if (flag == false){
            final CustomDialog.Builder builder = new CustomDialog.Builder(context);
            builder.setTitle("相册和文件存储权限申请");
            builder.setMessage("开启相册和文件存储权限，为了您可以使用设置个人头像、个人主页背景、发布带图的内容以及保存图片文件服务。");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SPManageUtils.getInstance(context).putSPBoolean("pictureNote", true);
                    if (callback != null){
                        callback.onResult(true, true);
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (callback != null){
                        callback.onResult(false, false);
                    }
                }
            });
            CustomDialog dialog = builder.create();
            dialog.show();
        }else {
            if (callback != null){
                callback.onResult(true, false);
            }
        }

    }

    //拍照权限
    public static void showCamaraNote(Context context, PermissionCallback callback){
        Boolean flag = SPManageUtils.getInstance(context).getSPBoolean("camaraNote", false);
        if (flag == false){
            final CustomDialog.Builder builder = new CustomDialog.Builder(context);
            builder.setTitle("相机权限申请");
            builder.setMessage("开启相机权限，为了您可以使用扫一扫、设置个人头像、个人主页背景、发布带图内容服务。");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SPManageUtils.getInstance(context).putSPBoolean("camaraNote", true);
                    if (callback != null){
                        callback.onResult(true, true);
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (callback != null){
                        callback.onResult(false, false);
                    }
                }
            });
            CustomDialog dialog = builder.create();
            dialog.show();
        }else {
            if (callback != null){
                callback.onResult(true, false);
            }
        }

    }

    //位置权限
    public static void isLocationNote(Context context, PermissionCallback callback){
        Boolean flag = SPManageUtils.getInstance(context).getSPBoolean("locationNote", false);
        if (flag == false){
            final CustomDialog.Builder builder = new CustomDialog.Builder(context);
            builder.setTitle("位置信息权限申请");
            builder.setMessage("开启位置信息权限，为了您可以使用定位信息来设置个人主页的地区信息或发布内容时的位置信息服务。");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SPManageUtils.getInstance(context).putSPBoolean("locationNote", true);
                    if (callback != null){
                        callback.onResult(true, true);
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (callback != null){
                        callback.onResult(false, false);
                    }
                }
            });
            CustomDialog dialog = builder.create();
            dialog.show();
        }else {
            if (callback != null){
                callback.onResult(true, false);
            }
        }
    }

    public static boolean hasSDCard(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(CustomApplication.mContext, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }else if (ActivityCompat.checkSelfPermission(CustomApplication.mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

}
